﻿using Coding4Fun.MissionControl.WP.Models;
using Coding4Fun.MissionControl.WP.ViewModels;
using Coding4Fun.Toolkit.Storage;
using System;
using System.Linq;
using System.Windows;

namespace Coding4Fun.MissionControl.WP.Misc
{
    public class CollectionHelper
    {
        public static bool CheckServerExists(Server server)
        {
            Server selected = (from c in MainPageViewModel.Instance.Servers 
                                     where c.Name == server.Name || c.Location == server.Location select c).FirstOrDefault();
            if (selected != null)
                return true;
            else
                return false;
        }

        public static bool RemoveServer(Server server)
        {
            try
            {
                RemoveTrailingFavorites(x=> x.ServerLocation == server.Location);

                MainPageViewModel.Instance.Servers.Remove(server);

                Serialize.Save(Constants.SERVERS_FILE, MainPageViewModel.Instance.Servers);

                return true;
            }
            catch
            {
                return false;
            }
        }

        internal static void RemoveTrailingFavorites(Func<Favorite,bool> predicate)
        {
            var favorites = MainPageViewModel.Instance.Favorites.Where(predicate).ToList();

            if (favorites.Count > 0)
            {
                foreach (var favorite in favorites)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            MainPageViewModel.Instance.Favorites.Remove(favorite);
                        });
                }

                Serialize.Save(Constants.FAVORITES_FILE, MainPageViewModel.Instance.Favorites);
            }
        }
    }
}
